package com.ebc.eservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ebc.eservice.mapper.CompanyMapper;
import com.ebc.eservice.mapper.RoleMapper;
import com.ebc.eservice.mapper.UserMapper;
import com.ebc.eservice.mapper.UserRoleMapper;
import com.ebc.eservice.pojo.*;
import com.ebc.eservice.pojo.pic.UploadFile;
import com.ebc.eservice.service.EbcUserService;
import com.ebc.eservice.util.CurrentUser;
import com.ebc.eservice.util.JsonResult;
import com.ebc.eservice.vo.admin.CompanyAccountRespVo;
import com.ebc.eservice.vo.admin.CompanyAccountVo;
import com.ebc.eservice.vo.admin.CompanyModifyReqVo;
import com.ebc.eservice.vo.admin.modifyPwdVo;
import com.ebc.eservice.vo.user.UserInfoReqVo;
import com.ebc.eservice.vo.user.UserInfoVo;
import com.ebc.eservice.vo.user.UserListVo;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author: Joey
 * @Description: 后端 - 设置 - 账户业务
 * @date:2022/9/19 10:11
 */

@Service
public class UserImp implements EbcUserService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserRoleMapper roleUserMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public JsonResult getRoleList() {

        QueryWrapper<EbcRole> wrapper = new QueryWrapper<>();
        //颗粒度
        wrapper.ne("id",3);
        wrapper.ne("id",4);
        List<EbcRole> roles = roleMapper.selectList(wrapper);
        return JsonResult.success(roles);
    }

    //添加企业账号
    @Override
    @Transactional(rollbackFor = Exception.class)  //如果要查 当前已插入的数据库就不用事务 不然数据库没更新
    public JsonResult addCompanyAccount(CompanyAccountVo accountVo) {
        JsonResult result=null;
        CurrentUser currentUser = new CurrentUser();
        if( !nameCheck(accountVo.getCompanyShortName())){
            result = JsonResult.fail("公司姓名重复");
        }else if(!phoneCheck(accountVo.getCompanyAccountPhone())){
            result = JsonResult.fail("手机号已存在");
        }else{
            //账号添加
            EbcUser ebcUser = new EbcUser();
            ebcUser.setName(accountVo.getCompanyShortName());
            ebcUser.setPhone(accountVo.getCompanyAccountPhone());//手机号默认作为账号
            ebcUser.setAccount(accountVo.getCompanyAccountPhone());//手机号默认作为账号
            ebcUser.setPassword(accountVo.getCompanyAccountPhone().substring(5,11));
            ebcUser.setDel(0);
            ebcUser.setOpen(1);
            ebcUser.setCreateId(currentUser.getCurrentEbcUser().getId());
            ebcUser.setCreator(currentUser.getCurrentEbcUser().getName());
            userMapper.insert(ebcUser);

            EbcUser user = userMapper.selectOne(Wrappers.<EbcUser>lambdaQuery()
                    .and(wrapper -> wrapper.eq(EbcUser::getPhone, accountVo.getCompanyAccountPhone()))
                    .last("limit 1"));
            //添加权限
            EbcUserRole userRole = new EbcUserRole();
            userRole.setRoleId(3).setUserId(user.getId());//权限默认3 企业管理员
            userRoleMapper.insert(userRole);

            //添加公司   公司简介在 个性化简介修改更新填充
            EbcCompany company = new EbcCompany();
            company
                .setName(accountVo.getCompanyName())
                .setShortName(accountVo.getCompanyShortName())
                .setOpen(1)
                .setPossessorId(user.getId())//公司持有人id
                .setCreateId(101); //自动获取当前登录的对象 一般是公司管理员
            companyMapper.insert(company);

            EbcCompany ebcCompany=companyMapper.selectOne(Wrappers.<EbcCompany>lambdaQuery()
                    .and(wrapper -> wrapper.eq(EbcCompany::getName, accountVo.getCompanyAccountName()))
                    .or(wrapper -> wrapper.eq(EbcCompany::getShortName, accountVo.getCompanyShortName()))
                    .last("limit 1"));

            result = JsonResult.success("添加成功，账户id: "+ebcCompany.getId());
        }

        return result;
    }

    @Override
    public JsonResult addCompanyPic(Integer companyId, MultipartFile companyFile) throws IOException {
        JsonResult result=null;
        UploadFile uploadFile = new UploadFile();
        Query query = new Query(Criteria.where("companyId").is(companyId));
        UploadFile file = mongoTemplate.findOne(query,UploadFile.class);
        if(file!=null){ //更新
            file.setContent(new Binary(companyFile.getBytes()));
            file.setName(companyFile.getOriginalFilename());
            file.setUpdateTime(new Date());
            file.setCompanyId(companyId);
            file.setContentType(companyFile.getContentType());
            file.setSize(companyFile.getSize());
            mongoTemplate.save(file);
            result = JsonResult.success("公司id-> "+companyId+",照片更新");
        }else{  //新增
            uploadFile.setContent(new Binary(companyFile.getBytes()));
            uploadFile.setName(companyFile.getOriginalFilename());
            uploadFile.setCreatedTime(new Date());
            uploadFile.setCompanyId(companyId);
            uploadFile.setContentType(companyFile.getContentType());
            uploadFile.setSize(companyFile.getSize());
            UploadFile save = mongoTemplate.save(uploadFile);
            result = JsonResult.success("公司id-> "+companyId+",照片新增");
        }
        return result;
    }


    //获取公司列表
    @Override
    public JsonResult getCompanyAccountList(int current, int size) {
        //分页条件
//        QueryWrapper<EbcUserRole> wrapper = new QueryWrapper<>();
//        wrapper.le("role_id",2);//role_id小于等于2的权限
        Page<CompanyAccountRespVo> page = new Page<>(current,size,false);
        IPage<CompanyAccountRespVo> studentAndMajorVOIPage = companyMapper.getCompanyAccountList(page);
        List<CompanyAccountRespVo> accountList = studentAndMajorVOIPage.getRecords();
        return JsonResult.success(accountList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult ModifyCompanyInfo(CompanyModifyReqVo reqVo) throws IOException {
        JsonResult result=null;
        //验证手机号
        if( !nameCheck(reqVo.getCompanyName())){
            result = JsonResult.fail("公司姓名重复");
        }else if(!phoneCheck(reqVo.getManagerPhone())){
            result = JsonResult.fail("手机号已存在");
        }else{
            //修改user
            EbcUser ebcUser = userMapper.selectById(reqVo.getPossessorId());
            ebcUser.setPhone(reqVo.getManagerPhone()).setName(reqVo.getManagerName());
            userMapper.updateById(ebcUser);
            //修改公司信息
            EbcCompany ebcCompany = companyMapper.selectById(reqVo.getCompanyId());
            ebcCompany.setName(reqVo.getCompanyName()).setShortName(reqVo.getShortName());
            //照片更新
            UserImp imp = new UserImp();
            imp.updateCompanyPic(reqVo.getCompanyId(), reqVo.getFile());

            result = JsonResult.success("修改成功");
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateCompanyPic(Integer companyId, MultipartFile companyFile) throws IOException {
        UploadFile uploadFile = new UploadFile();
        Query query = new Query(Criteria.where("companyId").is(companyId));
        UploadFile file = mongoTemplate.findOne(query,UploadFile.class);
        if(file!=null){ //更新
            file.setContent(new Binary(companyFile.getBytes()));
            file.setName(companyFile.getOriginalFilename());
            file.setUpdateTime(new Date());
            file.setCompanyId(companyId);
            file.setContentType(companyFile.getContentType());
            file.setSize(companyFile.getSize());
            mongoTemplate.save(file);
        }else{  //新增
            uploadFile.setContent(new Binary(companyFile.getBytes()));
            uploadFile.setName(companyFile.getOriginalFilename());
            uploadFile.setCreatedTime(new Date());
            uploadFile.setCompanyId(companyId);
            uploadFile.setContentType(companyFile.getContentType());
            uploadFile.setSize(companyFile.getSize());
            UploadFile save = mongoTemplate.save(uploadFile);
        }
    }

    @Override
    public JsonResult UpdateUseStatus(Integer companyId,Integer status) {
        if(status == 1){ //关闭
            companyMapper.ModifyClose(companyId);
        }else if(status == 0){
            companyMapper.ModifyOpen(companyId);
        }else{
            return JsonResult.fail("验证出错,请修改参数重新尝试");
        }
        return JsonResult.success("修改成功");
    }

    /*****************************             ************************************************/
    /*****************************   账号管理    ************************************************/
    /*****************************             ************************************************/
    /*****************************             ************************************************/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addNewAccount(UserInfoReqVo userInfoVo) {
        JsonResult result;
        CurrentUser currentUser = new CurrentUser();
        if( !nameCheck(userInfoVo.getUsername())){
           result = JsonResult.fail("用户名已被使用");
       }else if(!phoneCheck(userInfoVo.getPhone())){
           result = JsonResult.fail("手机号已被注册");
       }else{
           EbcUser ebcUser = new EbcUser();
           ebcUser.setName(userInfoVo.getUsername());
           ebcUser.setPhone(userInfoVo.getPhone());//手机号默认作为账号
           ebcUser.setAccount(userInfoVo.getPhone());//手机号默认作为账号
           ebcUser.setPassword(userInfoVo.getPhone().substring(5,11));
           ebcUser.setDel(0);
           ebcUser.setOpen(1);
           ebcUser.setCreateId(currentUser.getCurrentEbcUser().getId());
           ebcUser.setCreator(currentUser.getCurrentEbcUser().getName());

           if(userInfoVo.getRoleId() == 1){
               ebcUser.setRemark("员工");
           }else if(userInfoVo.getRoleId() == 2){
               ebcUser.setRemark("用户");
           }
           userMapper.insert(ebcUser);
           EbcUser user = userMapper.selectOne(Wrappers.<EbcUser>lambdaQuery()
                   .and(wrapper -> wrapper.eq(EbcUser::getAccount, userInfoVo.getPhone()))
                   .last("limit 1"));
           //.or()
           //.eq(EbcUser::getPhone, username)
           //增加权限
           EbcUserRole userRole = new EbcUserRole();
           userRole.setRoleId(userInfoVo.getRoleId()).setUserId(user.getId());
           userRoleMapper.insert(userRole);
           result = JsonResult.success("账户添加成功");
       }
        return result;
    }

    //用于账户管理的员工和用户查看 [不包括企业管理员]
    @Override
    public JsonResult getUserList(int current, int size) {
        //分页条件
        QueryWrapper<EbcUserRole> wrapper = new QueryWrapper<>();
        wrapper.le("r.id",2);//role_id小于等于2的权限
        wrapper.eq("u.del",0); // user u
        Page<UserListVo> page = new Page<>(current,size,false);
        IPage<UserListVo> studentAndMajorVOIPage = userMapper.getUserListXmlPage(page, wrapper);
        List<UserListVo> userList = studentAndMajorVOIPage.getRecords();
        return JsonResult.success(userList);
    }

    @Override
    public JsonResult getUserByInfo(UserInfoVo userInfoVo) {
        JsonResult result = null;
        //多条件查询用户
        List<EbcUser> list = userMapper.selectList(Wrappers.<EbcUser>lambdaQuery()
                .and(wrapper -> wrapper
                .eq(EbcUser::getId, userInfoVo.getId()))
                .or()
                .eq(EbcUser::getPhone, userInfoVo.getPhone())
                .or()
                .eq(EbcUser::getName, userInfoVo.getUsername()));
        if(list.size()==0){
            result = JsonResult.fail("没有查到此信息");
        }else{
            result = JsonResult.success(list);
        }
        return result;
        //分页
//        Page<EbcUser> page = new Page<>(1, 5);//currentPage pageSize
//        QueryWrapper<EbcUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("del",1);
//        ebcUserMapper.selectPage(page,queryWrapper);
//        page.getRecords().forEach(System.out::println);
//        List<EbcUser> records = page.getRecords();
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public JsonResult updateUserInfo(UserInfoVo userInfoVo) {
        //更新用户
        JsonResult result;
        if( !nameCheck(userInfoVo.getUsername())){
            result = JsonResult.fail("姓名重复");
        }else if(!phoneCheck(userInfoVo.getPhone())){
            result = JsonResult.fail("手机号已被注册");
        }else{
            EbcUser ebcUser = userMapper.selectById(userInfoVo.getId());
            ebcUser.setName(userInfoVo.getUsername());
            ebcUser.setPhone(userInfoVo.getPhone());    //手机号默认作为账号
            ebcUser.setAccount(userInfoVo.getPhone());
            userMapper.updateById(ebcUser);
            //修改权限 根据roleId获取权限
            EbcUserRole userRole = roleUserMapper.selectOne(
                    Wrappers.<EbcUserRole>lambdaQuery().and(wrapper ->
                            wrapper.eq(EbcUserRole::getUserId,userInfoVo.getId())));
            userRole.setRoleId(userInfoVo.getRoleId());
            roleUserMapper.updateById(userRole);
            result = JsonResult.success("账户修改成功");
        }
        return result;
    }

    @Override
    public JsonResult deleteUserById(Integer id) {
        int delete = userMapper.deleteById(id);//逻辑删除
        if(delete > 0 ){
            return JsonResult.success("账户删除成功");
        }
        return JsonResult.fail("删除失败,用户异常");
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public JsonResult resetPassword(Integer userId) {
        //重置密码为手机号后6位
        EbcUser user = userMapper.selectById(userId);
        user.setPassword(user.getPhone().substring(5,11));
        int i = userMapper.updateById(user);
        if(i < 0){
            return JsonResult.fail("重置失败");
        }
        return JsonResult.success("重置成功: 密码为 "+user.getPassword());
    }

    //管理员 -修改密码
    @Override
    @Transactional(rollbackFor=Exception.class)
    public JsonResult modifyPwd(modifyPwdVo mPVo) {
        // id  newpwd
        EbcUser ebcUser = userMapper.selectById(mPVo.getUserId());
        if(ebcUser.getPassword().equals(mPVo.getNewPassword())){
            return JsonResult.fail("密码重复，修改失败");
        }else{
            ebcUser.setPassword(mPVo.getNewPassword());
            userMapper.updateById(ebcUser);
        }
        return JsonResult.success("id:"+mPVo.getUserId()+",密码修改成功");
    }

    /******* 信息检查 *******/

    private boolean nameCheck(String name){
        System.out.println("当前name-> "+name);
        List<EbcUser> one = userMapper.selectList(Wrappers.<EbcUser>lambdaQuery()
                .and(wrapper -> wrapper.eq(EbcUser::getName, name)));
        return one.size() == 0;
    }
    private boolean phoneCheck(String phone){
        System.out.println("当前phone-> "+phone);
        List<EbcUser> one = userMapper.selectList(Wrappers.<EbcUser>lambdaQuery()
                .and(wrapper -> wrapper.eq(EbcUser::getPhone, phone)));
        return one.size() == 0;
    }
}
